/* eslint-disable react-hooks/exhaustive-deps */
"use client";

import { Pagination, Table } from "antd";
import { useEffect, useState } from "react";
import { GetTask } from "../api/operation/home";
import type { Pager } from "../../../utils/publictype";
import { getUserAccount } from "../../../utils/defender";
import { TableDataType } from "../../../utils/publicFuc";
import { useRouter } from "next/navigation";

interface TableData {
  rowseq: number;
  docid: string;
  badge: string;
  chinese_name: string;
  created_date: string;
  flow_phase: string;
  flow_code: string;
}

export default function Page() {
  const router = useRouter();
  const [sytanxFlag, setSytanxFlag] = useState(false);
  const [pager, setPager] = useState<Pager>({
    current: 1,
    count: 0,
    pagesize: 10,
  });
  const [datasource, setDataSource] = useState<TableData[]>([]);

  useEffect(() => {
    if (!getUserAccount()) {
      router.push("/");
    }
    const pagesize = Math.floor((document.body.clientHeight - 250) / 55) - 2;
    const param = {
      ...pager,
      pagesize: pagesize,
      username: getUserAccount(),
      type: "count",
    };
    GetTask(JSON.stringify(param))
      .then((resC: any) => {
        setSytanxFlag(false);
        if (resC[0][0].count > 0) {
          param.type = "list";
          GetTask(JSON.stringify(param))
            .then((res: any) => {
              if (res[0].length > 0) {
                const temp: TableData[] = TableDataType(res[0]);
                setDataSource(temp);
                setPager({
                  ...pager,
                  count: resC[0][0].count,
                  pagesize: pagesize,
                });
              }
            })
            .catch(() => {
              setSytanxFlag(true);
            });
        }
      })
      .catch(() => {
        setSytanxFlag(true);
      });
  }, []);

  const changeCurr = async (e: number) => {
    const param = {
      ...pager,
      current: e,
      username: getUserAccount(),
      type: "list",
    };
    GetTask(JSON.stringify(param)).then((res: any) => {
      if (res[0].length > 0) {
        const temp: TableData[] = TableDataType(res[0]);
        setDataSource(temp);
        setPager({
          ...pager,
          current: e,
        });
      }
    });
  };

  const GOTO = (docid: string) => {
    router.push("./interview", {});
    const selOne = datasource.filter((item) => item.docid === docid)[0];
    let url = "";
    if (
      selOne.flow_code === "interview" ||
      selOne.flow_code === "interview_sign_A" ||
      selOne.flow_code === "interview_sign_B"
    ) {
      url = "/dashboard/interview?docid=" + docid;
    } else if (
      selOne.flow_code === "improve" ||
      selOne.flow_code === "improve_check" ||
      selOne.flow_code === "improve_record_sign_A" ||
      selOne.flow_code === "improve_record_sign_B" ||
      selOne.flow_code === "improve_check_sign_A" ||
      selOne.flow_code === "improve_check_sign_B"
    ) {
      url = "/dashboard/improve?docid=" + docid;
    } else if (
      selOne.flow_code === "manager_approve_1" ||
      selOne.flow_code === "manager_approve_2" ||
      selOne.flow_code === "manager_approve_3"
    ){
      url = "/dashboard/manager?docid=" + docid;
    }
      router.push(url);
  };

  //#region  表格設定
  const getColumns = [
    {
      title: "單號",
      dataIndex: "docid",
      key: "docid",
      width: 150,
      render: (docid: any) => {
        return (
          <div>
            <span onClick={() => GOTO(docid)} className="maintaince-link">
              {docid}
            </span>
          </div>
        );
      },
    },
    {
      title: "姓名",
      dataIndex: "chinese_name",
      key: "chinese_name",
      width: 120,
    },
    {
      title: "創建日期",
      dataIndex: "created_date",
      key: "created_date",
      width: 120,
    },
    {
      title: "所處流程",
      dataIndex: "flow_phase",
      key: "flow_phase",
      width: 100,
    },
  ];

  const getTable = () => {
    if (sytanxFlag) {
      return <h2>系統異常，請聯繫系統管理者</h2>;
    }
    if (datasource.length > 0) {
      return (
        <>
          <div className="pagemain-box">
            <Table
              dataSource={datasource.map((item) => ({
                ...item,
                key: item.rowseq,
              }))}
              bordered={true}
              pagination={false}
              className="datasource-table"
              columns={getColumns}
              style={{ marginTop: "5px" }}
              scroll={{ x: "max-content" }}
            ></Table>
            <Pagination
              current={pager.current}
              pageSize={pager.pagesize}
              style={{ marginTop: "20px" }}
              total={pager.count}
              onChange={(e) => {
                changeCurr(e);
              }}
            />
          </div>
        </>
      );
    } else {
      return <h2>您沒有代辦事項需要處理</h2>;
    }
  };

  //#endregion

  return <div className="main-content">{getTable()}</div>;
}
